<?php

/**
 * This is the model class for table "conso_edf_jours".
 *
 * The followings are the available columns in table 'conso_edf_jours':
 * @property string $dte
 * @property string $hp
 * @property string $hc
 */
class ConsoEdfJour extends CActiveRecord {

    // Champs calculés
    public $dteGroup = null;
    
    
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return ConsoEdfJour the static model class
     */
    public static function model($className = __CLASS__) {
	  return parent::model($className);
    }


    /**
     * @return string the associated database table name
     */
    public function tableName() {
	  return 'mesures_consoedf_jours';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	  // NOTE: you should only define rules for those attributes that
	  // will receive user inputs.
	  return array(
		array('dte, hp, hc', 'safe'),
		// The following rule is used by search().
		// Please remove those attributes that should not be searched.
		array('dte, hp, hc', 'safe', 'on' => 'search'),
	  );
    }

    /**
     * @return array relational rules.
     */
    /*
    public function relations() {
	  // NOTE: you may need to adjust the relation name and the related
	  // class name for the relations automatically generated below.
	  return array(
	  );
    }
     * 
     */

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	  return array(
		'dte' => 'Date',
		'hp' => 'Conso heures pleines',
		'hc' => 'Conso Heures creuses',
	  );
    }

    
    
      /*
     * Enregistrement des données journalières
     * 
     * @param $dte date date à calculer
     */  
 
    public function getParJour($dte) {
	  
	  // Récupération de la moyenne journalière
	  $criteria = new CDbCriteria();
	  $criteria->select = 'SUM(diffhp) AS hp, SUM(diffhc) AS hc, SUM(difftps) as duree ';
	  $criteria->condition = "dte LIKE :dte";
	  $criteria->group = 'SUBSTR(dte, 1,10)';
	  $criteria->params = array('dte' => $dte.'%');


	  $result = ConsoEdfReleve::model()->findAll($criteria);
//print_r($result[0]);
	  if(count($result) != 1){
		Yii::log('Données des relevés invalides pour le '.$dte, 'warning', 'mesures.ConsoEdfJour');

	  }
	  else {
	
		// Recalage des heures pleines sur 24h
		// (pas nécessaire pour les pc car pas à cheval sur 2 jours (2-7h, 14h-17h)
		$hp = round($result[0]->hp / $result[0]->duree * 1440, 0);

		// Récupération des valeurs
		$this->setAttributes(array(
		    'dte' => $dte,
		    'hp' => $hp,
		    'hc' => $result[0]->hc,
			)
		);
//print_r($this);
		// Aout ou mise à jour du jour
		$this->save();
	  }
    }   
    
  
    
    
    
     /*
     * Génération des graphiques
     * 
     */   
    
    public static function getGraphJournalier() {
	  $graphOptions = array(
		'title' => array('text' => 'Consommation journaliere'),
	  );
	  $graphData = ConsoEdfJour::getGraphData(array('groupby' => 'dte', 'duree' => '3 MONTH'));
	  return array_merge($graphOptions, $graphData);
    }
    
    public static function getGraphMensuel() {
	  $graphOptions = array(
		'title' => array('text' => 'Consommation mensuelle'),
	  );
	  $graphData = ConsoEdfJour::getGraphData(array('groupby' => 'SUBSTR(dte, 1, 7)', 'duree' => '2 YEAR'));
	  return array_merge($graphOptions, $graphData);
    }

  
    public static function getGraphAnnuel() {
	  $graphOptions = array(
		'title' => array('text' => 'Consommation annuelle'),
	  );
	  $graphData = ConsoEdfJour::getGraphData(array('groupby' => "(SUBSTR(dte, 1, 4) || '-06-01')", 'duree' => '10 YEAR'));
	  return array_merge($graphOptions, $graphData);
    }   
    
    /*
     * Récupération des données de consommation EDF pour les graphs
     * @options array : liste des paramètres (groupby, duree)
     * @return array
     */
    public static function getGraphData($options = array()) {
	  $criteria = new CDbCriteria();
	  $criteria->select = $options['groupby'] . ' AS dteGroup, SUM(hp) AS hp, SUM(hc) AS hc ';
	  $criteria->condition = 'dte >= NOW() - INTERVAL '. $options['duree'];
	  $criteria->group = 'dteGroup';
	  $criteria->order = 'dteGroup';
	  //$criteria->params = array('duree' => $options['duree']);

	  $result = ConsoEdfJour::model()->findAll($criteria);

	  $hp = array();
	  $hc = array();

	  foreach ($result as $rs) {

		$dte = 1000 * strtotime($rs->dteGroup);
		$dte = (string) $dte;

		$hp[] = array((float)$dte, round($rs->hp / 1000, 0));
		$hc[] = array((float)$dte, round($rs->hc / 1000, 0));
		
	  }

	  // Nettoyage de la chaine
	  //$hp = substr($hp, 1);
	  // $hc = substr($hc, 1);

	  $graph = array(
		//'Container' => 'conso' . $regroup,
		'chart' => array('type' => 'column'),
		'yAxisTitle' => 'kWh',
		'xAxis' => array('type' => 'datetime'),
		'dataLabel' => true,
		'plotOptions' => array(
		    'column' => array(
			  'stacking' => 'normal',
			  'borderWidth' => 0,
		    )
		),
		'series' => array(
		    array(
			  'name' => 'Heures pleines',
			  'data' => $hp,
			  'color' => '#ED651B',
		    ),
		    array(
			  'name' => 'Heures creuses',
			  'data' => $hc,
			  'color' => '#69CD4B',
		    ),
		),
	  );
	  return $graph;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    /*
      public function search()
      {
      // Warning: Please modify the following code to remove attributes that
      // should not be searched.

      $criteria=new CDbCriteria;

      $criteria->compare('dte',$this->dte,true);
      $criteria->compare('hp',$this->hp,true);
      $criteria->compare('hc',$this->hc,true);

      return new CActiveDataProvider($this, array(
      'criteria'=>$criteria,
      ));
      }
     * 
     */
}